<?php


namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;

class DataSyncController extends Controller
{
    const KEY = 'G2nCha2f1ZCszDuebLR1KxJS844Ud4KS';

    public function request(Request $request)
    {
        if(!$this->verify($request->header('authorization'))) {
            return Response::json(['return_code'=>'FAIL', 'return_msg'=>'Verify sign failed']);
        }

        $items = [];

        $files = $request->file();


        foreach ($files as $key=>$file) {
            //上传文件无效
            if(!$file->isValid()) {
                return Response::json(['return_code'=>'FAIL', 'return_msg'=>'Illegal file']);
            }

            //检查文件类型是否为'.sql'
            if($file->getClientOriginalExtension() != 'sql') {
                return Response::json(['return_code'=>'FAIL', 'return_msg'=>'Illegal file type']);
            }

            //获取上传文件路径、检查文件大小
            $origName = $file->getRealPath();
            if (filesize($origName) >= 2048000) {
                return Response::json(['return_code'=>'FAIL', 'return_msg'=>'The file must be less than 2 MB']);
            }

            $clientOriginalName = $file->getClientOriginalName();

            //重命名上传文件
            $newName = storage_path('uploads') . DIRECTORY_SEPARATOR  . date('YmdHis')  . str_random(5) . "_" . $clientOriginalName;

            //上传文件挪至指定位置
            if(!move_uploaded_file($origName, $newName)) {
                return Response::json(['return_code'=>'FAIL', 'return_msg'=>$key . ' File upload failed']);
            }

            //上传文件路径进入数组
            $items[$key] = $newName;
        }

        //product和zone表都上传成功则继续处理
        if(!array_key_exists('tbl_bill_open_product', $items) || !array_key_exists('tbl_bill_open_zone', $items)) {
            return Response::json(['return_code'=>'FAIL', 'return_msg'=>'File upload failed']);
        }

        foreach ($items as $key=>$item) {
            //检查sql文件是否存在
            if(!file_exists($item)) {
                return Response::json(['return_code'=>'FAIL', 'return_msg'=>'File does not exists']);
            }
            //获取sql文件内容
            $sql = file_get_contents($item);
            //清空表数据
            DB::table($key)->truncate();
            //执行sql插入数据
            if(!DB::insert($sql)) {
                return Response::json(['return_code'=>'FAIL', 'return_msg'=> $key . ' insert fail']);
            }
            //删除sql文件
            @unlink($item);
        }

        return Response::json(['return_code'=>'SUCCESS', 'return_msg'=>'Sync success']);
    }

    //验签
    private function verify($sign)
    {
        return md5(self::KEY) == $sign;
    }
}
